package com.ulook.lookplanet.data.repository;

import android.content.SharedPreferences;

import com.ulook.lookplanet.common.DataFile;
import com.ulook.lookplanet.data.model.BaseUser;
import com.ulook.lookplanet.data.source.LoginDataSource;
import com.ulook.lookplanet.data.model.TUser;
import com.ulook.lookplanet.util.SharedPreUtil;
import com.ulook.lookplanet.util.TimeUtil;
import com.ulook.lookplanet.util.net.ResponseCallback;

/**
 * Class that requests authentication and user information from the remote data source and
 * maintains an in-memory cache of login status and user credentials information.<br>
 * 该类从远程数据源请求身份验证和用户信息，并维护登录状态和用户凭据信息的内存缓存。
 *
 * @author: L1998
 * @data: 2021/3/24
 */
public class LoginRepository {

    private static volatile LoginRepository instance;

    private LoginDataSource dataSource;

    private BaseUser user = null;

    // private constructor : singleton access
    private LoginRepository(LoginDataSource dataSource) {
        this.dataSource = dataSource;
    }

    public static LoginRepository getInstance(LoginDataSource dataSource) {
        if (instance == null) {
            instance = new LoginRepository(dataSource);
        }
        return instance;
    }


    public boolean isLoggedIn() {
        return user != null;
    }

    /**
     * 退出登陆
     */
    public void logout() {
        user = null;
        SharedPreferences.Editor editor = SharedPreUtil.getEditor(DataFile.LOGIN_DATA);
        editor.putInt("id", 0);
        editor.putString("name", "游客");
        editor.putString("password", "");
        editor.apply();
        dataSource.logout();
    }


    /**
     * 处理登陆请求
     */
    public void login(String username, String password, ResponseCallback callback) {
        // 数据源获取
        dataSource.login(username, password, callback);
    }

    /**
     * 注册账号
     */
    public void register(String nickname, String username, String password, ResponseCallback callback){
        dataSource.register(nickname, username, password, callback);
    }

    public void setLoggedInUser(TUser user) {
        this.user = user;
        // 如果用户凭据将缓存在本地存储中，对其进行加密
        SharedPreferences.Editor editor = SharedPreUtil.getEditor(DataFile.LOGIN_DATA);
        editor.putInt("id", user.getId());
        editor.putString("name", user.getName());
        editor.putString("password", user.getPassword());
        editor.putString("loginTime", TimeUtil.getCurrDateTime());
        editor.apply();
    }


}